<template>
<div>
    <page-header-wrapper></page-header-wrapper>
    <a-card style="margin-top: 20px">
        <div class="table-page-search-wrapper">
            <a-form :form="searchForm" layout="inline">
                <a-row :gutter="48">
                    <SearchFormItems :searchKeys="OrderPhotoSearchKeys" :md="{span:8}" :sm="{span:24}" :advanceVal="advanced" :getDataWithKey="getDataWithKey">
                    </SearchFormItems>
                    <a-col :md="(!advanced && 8) || 6" :sm="6" class="advanced_butns">
                        <span class="table-page-search-submitButtons" :style="
                            (advanced && { float: 'right', overflow: 'hidden' }) || {}
                        ">
                            <a-button @click="reset">重置</a-button>
                            <a-button type="primary" @click="search">查询</a-button>
                            <a @click="toggleAdvanced">
                                {{ advanced ? '收起' : '展开' }}
                                <a-icon :type="advanced ? 'up' : 'down'" />
                            </a>
                        </span>
                    </a-col>
                </a-row>
            </a-form>
        </div>
    </a-card>
    <div class="cont_box">
        <div class="table_header flex-between">
            <div class="table_name">{{pageTitle}}</div>
            <div class="table_butns flex-end">

                <a-button size="default" type="primary"  @click="exportSetting()">
                    下载设置
                </a-button>
                <a-button size="default" type="default" :disabled="!selectedRowKeys.length" @click="getExcel">
                    生成Excel
                </a-button>
                <a-button size="default" type="primary" :disabled="!selectedRowKeys.length" @click="zipDownload">
                    压缩包复制
                </a-button>
                <a-button size="default" type="default" :disabled="!selectedRowKeys.length" @click="batchCancel">
                    批量作废
                </a-button>
            </div>
        </div>
        <a-table :columns="OrderPhotoColumn" :dataSource="dataSource" :pagination="pagination" :rowKey="(it,index) => it.id+index " :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange
        }" :loading="loading" binvested :scroll="{ x: 1500 }">
            <a-badge slot="type" slot-scope="text" status="default" :text="getTypeName(text.type)" />
            <div slot="url1" slot-scope="record" class="two_line txt-over-2">
                <a-tooltip>
                    <template slot="title" v-if="record.url1">
                        {{record.url1}}
                    </template>
                    <a :href="record.url1" target="_blank">{{ record.url1 || '-'  }}</a>
                </a-tooltip>
            </div>
            <a-tooltip slot="picSource" slot-scope="record">
                <template slot="title" v-if="record.picSource">
                    {{record.picSource}}
                </template>
                <div class="txt-over-2 two_line"><a>{{ record.picSource || '-' }}</a></div>
            </a-tooltip>
            <!-- <a slot="picSource" slot-scope="record">{{ record.picSource || '-' }}</a> -->
            <div slot="url2" slot-scope="record" style="height:100px;width: 100px;">
                <img class="table_img"  :src="record.url2" @click="zoomPic(record.url2)" />
            </div>
            <a-tooltip slot="errorMsg" slot-scope="record">
                <template slot="title" v-if="record.errorMsg">
                    {{record.errorMsg}}
                </template>
                <div class="txt-over-2 two_line"><a>{{ record.errorMsg || '-' }}</a></div>
            </a-tooltip>
            <a-badge slot="status" slot-scope="text" :status="text.status == 1 ?'success':'error'" :text="getStatusName(text.status)" />
            <span slot="operation" slot-scope="text, record">
                <a-button size="small" type="link"  @click="showModal(record)">
                    编辑
                </a-button>
                <a-button size="small" type="link" @click="cancelOrder(record)">
                    作废
                </a-button>
            </span>
        </a-table>
        <pagination :total="total" :page.sync="page" :size.sync="size" :onPageSizeChange="onPageSizeChange" :onShowSizeChange="onShowSizeChange" />
        <a-modal title="编辑" v-model="editVisible" destroyOnClose @ok="sureModal" width="600px">
            <div class="modal_body_cont">
                <a-form :form="modalForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                    <modalFormItem :searchKeys="PhotoModalKeys" :getDataWithKey="getDataWithKey"></modalFormItem>
                </a-form>
            </div>
        </a-modal>
    </div>
    <PreviewPic :isShowPic="previewVisible" @closePreviewpic="previewHandleCancel" :previewImage="previewImage"></PreviewPic>
    <a-modal title="下载设置" v-model="settingVisible" 
        :maskClosable="false" 
        :closable="false" 
        destroyOnClose 
        @ok="sureSetting" 
        @cancel="cancelSetting" 
        width="600px" 
        :bodyStyle="{height:'500px',overflowY:'auto'}">
        <div class="modal_body_cont">
            <a-table
                :columns="SettingDownloadColumn"
                :dataSource="settingList"
                :pagination="false"
                :rowKey="(it) => it.fieldId"
                :rowSelection="{
                    selectedRowKeys: selectedSettingRowKeys,
                    onChange: onSettingSelectChange
                }"
                binvested
            >
            </a-table>
        </div>
    </a-modal>
</div>
</template>

<script>
import PreviewPic from "../../comps/PreviewPic.vue"
import {
    OrderPhotoSearchKeys,
    OrderPhotoColumn,
    PhotoModalKeys,
} from './config'
import {
    photoStatusEnum,
    photoList,
    photoToExcel,
    picZip,
    picCancel,
    picUpdate,
    generateToExcel
} from '@/api/order'
import { checkUserExportSetting,saveUserExportSetting} from '@/api/company'

export default {
    name: 'OrderList',
    components:{PreviewPic},
    data() {
        return {
            pageTitle:'',
            OrderPhotoSearchKeys,
            OrderPhotoColumn,
            // 高级搜索 展开/关闭
            advanced: false,
            // 查询参数
            queryParam: {},
            dataSource: [],
            pagination: false,
            page: 1,
            size: 50,
            total: 0,
            loading: false,
            selectedRowKeys: [],
            selectedRows: [],
            editVisible: false,
            searchForm:this.$form.createForm(this, { name:'order_photo_search' }),
            modalForm: this.$form.createForm(this, {
                name: "order_photo_modal"
            }),
            PhotoModalKeys,
            statusArrs: [],
            typeArrs:[{key:1,value:'设计'},{key:2,value:'素材'}],
            orderId:'',
            previewVisible: false,
            previewImage: "",
            settingVisible:false,
            settingList:[],
            SettingDownloadColumn:[    { title: '名称', align: 'center', dataIndex:'bizName' }, ],
            selectedSettingRowKeys:[],
            selectedSettingRows: [],
        }
    },
    computed: {
        getDataWithKey() {
            return key => {
                switch (key) {
                    case "type":
                        return this.typeArrs
                    case "status":
                        return this.statusArrs
                    default:
                        return [];
                }
            };
        },
    },
    created() {
        this.pageTitle = this.$route?.meta?.title
        this.getPhotoStatus()
        this.getList();
    },
    methods: {
        zoomPic(item) {
            this.previewImage = item;
            this.previewVisible = true;
        },
        previewHandleCancel() {
            this.previewVisible = false;
        },
        search() {
            this.page = 1;
            this.getList();
        },
        reset() {
            this.searchForm.resetFields();
            this.page = 1;
            this.getList();
        },
        async getPhotoStatus() {
            let status = await photoStatusEnum()
            this.statusArrs = status?.data
        },
        getTypeName(type){
            let tem = this.typeArrs.filter(item =>{return item.key == type}); 
            if(tem && tem[0]){
                return tem[0].value
            }else{
                return ''
            }
        },
        getStatusName(status){
            let tem = this.statusArrs.filter(item =>{return item.key == status}); 
            if(tem && tem.length>0){
                return tem[0]?.value
            }else{
                return ''
            }
        },
        onPageSizeChange(page, size) {
            this.selectedRowKeys = []
            this.page = page;
            this.getList(page, size);
        },
        onShowSizeChange(page, size) {
            this.selectedRowKeys = []
            this.page = page;
            this.size = size;
            this.getList(page, size);
        },
        getExcel(){
            let res = this.selectedRows.map((i) => {return i.id })
            generateToExcel({ids:res}).then(res =>{
                if(res.success){
                    this.$message.success(res?.message)
                }else{
                    this.$message.error(res?.message)
                }
                this.selectedRowKeys = []
                this.selectedRows =[]
            })
        },
        zipDownload(){
            let res = this.selectedRows.map((i) => {return i.orderNo })
            picZip({orderNo:res}).then(res =>{
                this.$message.success(res?.message)
                this.selectedRowKeys = []
                this.selectedRows =[]
            })
        },
        cancelOrder(record){
            this.$confirm({
                title: `确定要作废吗？`,
                content: '',
                okText: '作废',
                okType: 'danger',
                cancelText: '取消',
                onOk: () => {
                    picCancel({ids:[record.id]}).then(res =>{
                        this.$message.success('操作成功')
                        this.getList()
                    })
                },
            })
        },
        batchCancel(){
            picCancel({ids:this.selectedRowKeys}).then(res =>{
                this.$message.success('操作成功')
                this.selectedRowKeys = []
                this.getList()
            })
        },
        // 获取列表
        async getList(currentPage, currentSize) {
            this.loading = true
            const { page, size } = this;
            this.searchForm.validateFields(async (err, values) => {
                if (!err) {
                    let queryParam = this.searchForm.getFieldsValue(),orderNos = []
                    if(queryParam && queryParam.orderNos){
                        if(queryParam.orderNos.indexOf('\n')>-1){
                        orderNos = queryParam.orderNos.split('\n')
                        }else{
                        orderNos.push(queryParam.orderNos)
                        }
                    }
                    let params = {
                        pageNum: (currentPage) || (page),
                        pageSize: currentSize || size,
                        ...values,
                        orderNos
                    };
                    const res = await photoList(params)
                    this.total = res?.data?.total || 0;
                    this.dataSource = res?.data?.list || []
                    this.loading = false
                } else{
                    this.loading = false
                }
            })
        },
        showModal(record) {
            this.editVisible = true
            if(record){
                let {id,type,picSource,url1,url2,userName,skuName,errorMsg} = record
                    this.orderId = id
                    this.$nextTick(() => {
                    setTimeout(() => {
                        this.modalForm.setFieldsValue({type,picSource,url1,url2,userName,skuName,errorMsg})
                    },400)
                });
            }else{
                this.orderId = ''
                this.modalForm.resetFields()
            }
        },
        sureModal() {
            let {orderId} = this
                this.modalForm.validateFields(async (err,values) => {
                    if(!err){
                        let params = {
                            ...values,
                            id:orderId,
                        }
                        picUpdate(params).then(res =>{
                            this.$message.success('编辑成功')
                            this.orderId = ''
                            this.editVisible = false
                            this.getList()
                        })
                    }
                })
        },
        onSelectChange(selectedRowKeys, selectedRows) {
            this.selectedRowKeys = selectedRowKeys;
            this.selectedRows = selectedRows;
        },
        toggleAdvanced() {
            this.advanced = !this.advanced;
        },

        onSettingSelectChange(selectedRowKeys, selectedRows) {
            this.selectedSettingRowKeys = selectedRowKeys;
            this.selectedSettingRows = selectedRows;
        },
        cancelSetting(){
            this.selectedSettingRowKeys = []
            this.selectedSettingRows = []
        },
        sureSetting(){
            let params = {
                excelSettingList:this.selectedSettingRows
            }
            saveUserExportSetting(params).then(res =>{
                if(res?.success){
                    this.$message.success('操作成功')
                }else{
                    this.$message.error(res?.message)
                }
                this.selectedSettingRowKeys = []
                this.selectedSettingRows = []
                this.settingVisible = false
            })
        },
        async exportSetting(){
            let res = await checkUserExportSetting()
            this.settingVisible = true
            let temList = res?.data ?? []
            for(let i =0;i<temList.length;i++){
                if(temList[i].id){
                    this.selectedSettingRowKeys.push(temList[i].fieldId)
                    this.selectedSettingRows.push(temList[i])
                }
            }
            this.settingList = res?.data
        },
    },
};
</script>
